﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace XNA_Game_Framework
{
	public class Menu : Control
	{
		int index;
		internal List<MenuItem> menuItems;
		Theme.Menu theme;

		public string CurrentEntry
		{
			get { return menuItems[index].Text; }
		}

		public int CurrentIndex
		{
			get { return index; }
			set { index = value; }
		}

		public SpriteFont Font
		{
			get { return theme.font; }
			set { theme.font = value; }
		}

		public string GetEntry(int index)
		{
			return menuItems[index].Text;
		}

		public MenuItem GetMenuItem(int index)
		{
			return menuItems[index];
		}

		internal Texture2D SelectionBox
		{
			get { return theme.selectionBox; }
		}

		public override Vector2 Size
		{
			get { return new Vector2(theme.selectionBox.Width, theme.selectionBox.Height * menuItems.Count()); }
		}

		public Menu(object parent, InputHandler inputHandler, string name, Vector2 position, string[] entries, Theme.Menu theme, bool isMainMenu)
			: base(name, parent, position)
		{
			menuItems = new List<MenuItem>();
			this.theme = theme;
			CreateItems(inputHandler, entries);
			index = 0;

			if (isMainMenu)
			{
				inputHandler.UpKeyPressed += DecreaseIndex;
				inputHandler.DownKeyPressed += IncreaseIndex;
				inputHandler.EnterKeyPressed += OnItemChosen;
			}
		}

		private void CreateItems(InputHandler inputHandler, string[] items)
		{
			for (int i = 0; i < items.Count(); i++)
			{
				string text = items[i];
				menuItems.Add(new MenuItem(inputHandler, this, text));
			}

		}

		public void DecreaseIndex(object sender, KeyPressedEventArgs e)
		{
			index -= 1;
			if (index < 0)
			{
				index = menuItems.Count() - 1;
			}
		}

		public void IncreaseIndex(object sender, KeyPressedEventArgs e)
		{
			index += 1;
			if (index >= menuItems.Count())
			{
				index = 0;
			}
		}

		override internal bool OnLeftClick(MouseEventArgs e)
		{
			if (IsWithinBounds(e.Position) && Enabled)
			{
				menuItems[index].OnItemClicked();
				return true;
			}
			return false;
		}

		override internal bool OnMouseMoved(MouseEventArgs e)
		{
			if (IsWithinBounds(e.Position) && Enabled)
			{
				index = (int)(e.Y - ScreenPosition.Y) / theme.selectionBox.Height;
				return true;
			}
			return false;
		}

		public void OnItemChosen(object sender, KeyPressedEventArgs e)
		{
			menuItems[index].OnItemClicked();
		}

		internal override void Draw(SpriteBatch spriteBatch)
		{
			MenuDraw.Start(this, spriteBatch);
		}
	}
}
